package googleearthdownloader;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
import java.util.Vector;




import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.WindowConstants;

public class DownloadSystem {
	
	final boolean useproxy;
	final int VNUMBER;	
	
	// Variables
	private String[] baseURLs = new String[2];
	private String statusTextText;
	private int xstart, xend, ystart, yend, z, screenHeight, screenWidth, downloadThreadCount, workDoneCounter;
	
	private String imageAdress;
	private File pictureObjectDirectory, notFoundListFile;
	private FilesToDownloadList filesToDownload;
	private BufferedReader notFoundListReader;
	private BufferedWriter notFoundListWriter;
	
	private JFrame mainFrame;
	private JDialog statusFrame, downloadFrame;
	private JPanel statusPanel, downloadPanelTop, downloadPanelBottom;
	private JProgressBar statusDownloadProgress;
	private JLabel statusText, xStartLabel, xEndLabel, yStartLabel, yEndLabel, zHeightLabel;
	private JTextField xStartTextField, xEndTextField, yStartTextField, yEndTextField, zHeightTextField;
	private JButton downloadButton, cancelButton;
	private ActionListener downlaodAction, cancleButtonAction, loadFinishedAction;
	private Timer loadFinishedTimer;
	private BufferedImage previewImage;
	
	private SwingWorker<Void,BufferedImage> downloadWorker;
	private PropertyChangeListener pcl;
	
	private ProxySystem proxySystem;
	private boolean cancleDownload;
	
	private SystemLog systemLog;
	
	private int timeout;
	private int threadcount; 
	
	
	public DownloadSystem(ProxySystem proxySystem, JFrame mainFrame, SystemLog systemLog, int vNumber, boolean useproxy, int threadcount, int timeout){
		
		this.mainFrame= mainFrame;
		this.proxySystem = proxySystem;
		this.systemLog = systemLog;
		this.useproxy =useproxy;
		this.VNUMBER=vNumber;
		downloadThreadCount = threadcount;
		this.timeout = timeout;
		
		init();
		initUI();
	}
	private void downloadImages(int x,int xe,int y,int ye,int zh){
		
		xstart = x;
		xend = xe;
		ystart = y;
		yend =ye;
		z= zh;
	
		downloadWorker = new SwingWorker<Void, BufferedImage>(){
			
			@Override
			protected Void doInBackground() {
				
				cancleDownload = false;
				workDoneCounter=0;
				
				pictureObjectDirectory = new File(new File("").getAbsolutePath()+"//savedData//height "+z+"//");
				
				if(!pictureObjectDirectory.exists()){
					pictureObjectDirectory.mkdir();
				}
				
				filesToDownload = new FilesToDownloadList();
				
				systemLog.log("loading NotFoundList",SystemLog.INFO_MESSAGE);
				TreeSet<String> notFoundList = getNotFoundList();
				systemLog.log("NotFoundList loaded",SystemLog.INFO_MESSAGE);
				
				systemLog.log("loading FilesAlreadyOnDisk list",SystemLog.INFO_MESSAGE);
				TreeSet<String> filesAlreadyOnDisk = new TreeSet<String>(Arrays.asList(pictureObjectDirectory.list()));
				systemLog.log("FilesAlreadyOnDisk list loaded",SystemLog.INFO_MESSAGE);
				
				String currentImageFile;
				
				systemLog.log("Starting download list creation",SystemLog.INFO_MESSAGE);
				
				for(int i = 0; (i<=xend-xstart) && (!isDownloadCancelled()) ;i++){
					for(int q = 0;(q<=yend-ystart) && (!isDownloadCancelled());q++){
						
						currentImageFile= "x="+(i+xstart)+" y="+(q+ystart)+ " z="+z+".png";
						
						if(!filesAlreadyOnDisk.remove(currentImageFile)&&!notFoundList.remove("x="+(i+xstart)+"y="+(q+ystart)+"z="+z)){
							
							imageAdress = nextAdress((i+xstart),(q+ystart),z);
							
							try {
								filesToDownload.add(new DownloadableImage(i+xstart,q+ystart,z,new URL(imageAdress)));
							} catch (MalformedURLException e) {
								systemLog.log("Error while creating url and adding to filesToDownload",SystemLog.SHORT_ERROR_MESSAGE);
								e.printStackTrace();
							}
						}
						
						/*else{
							systemLog.log("We are lucky. File: " + currentImageFile + " is already on harddrive or on not found list.",SystemLog.INFO_MESSAGE);
						}*/	
						//TODO SystemLog.log slows down execution, maybe replace system log invoke later with swingworker or executor
					}
				}
				systemLog.log("finished download list creation",SystemLog.INFO_MESSAGE);
				
				/*
				for(int i = 0; (i<=xend-xstart) && (!isDownloadCancelled()) ;i++){
					for(int q = 0;(q<=yend-ystart) && (!isDownloadCancelled());q++){
						
						currentImageFile= new File(pictureObjectDirectory.getAbsolutePath()+"//x="+(i+xstart)+" y="+(q+ystart)+ " z="+z+".jpg");
						
						if(!currentImageFile.exists()&&!notFoundList.contains("x="+(i+xstart)+"y="+(q+ystart)+"z="+z)){
							
							imageAdress = nextAdress((i+xstart),(q+ystart),z);
							
							try {
								filesToDownload.add(new DownloadableImage(i+xstart,q+ystart,z,new URL(imageAdress)));
							} catch (MalformedURLException e) {
								systemLog.log("Error while creating url and adding to filesToDownload",SystemLog.SHORT_ERROR_MESSAGE);
								e.printStackTrace();
							}
						}
						else{
							systemLog.log("We are lucky. File: " + currentImageFile.getName() + " is already on harddrive or on not found list.",SystemLog.INFO_MESSAGE);
						}	
					}
				}*/
				
				systemLog.log("Starting worker thread creation",SystemLog.INFO_MESSAGE);
				
				for(int i=0;i<downloadThreadCount ;i++ ){
					
					new Thread(){
						
						DownloadableImage currentImageToDownload;
						boolean downloadable;
						File saveFile;
						URL imageURL;
						Proxy proxy;
						BufferedImage bi;
						URLConnection urlConnection;
						String absoluteFilePathPng;
						BufferedInputStream urlConnectionInputStream;
						
						@Override
						public void run(){
						
							while((currentImageToDownload = filesToDownload.checkOut(0))!= null && (!isDownloadCancelled())){
								downloadable = true;
								imageURL = currentImageToDownload.getImageURL();
								
								//TODO Bug image is name ipg but saved png
								
								absoluteFilePathPng = pictureObjectDirectory.getAbsolutePath()+"//x="+currentImageToDownload.getX()+" y="+currentImageToDownload.getY()+ " z="+currentImageToDownload.getZ()+".png";
								saveFile = new File(absoluteFilePathPng);
								
								while(downloadable && (!isDownloadCancelled())){
						
									proxy= proxySystem.nextProxy();
									bi=null;
									urlConnection=null;
									
									try {
										if (useproxy){
											urlConnection = imageURL.openConnection(proxy);
										}
										else{
											urlConnection = imageURL.openConnection();
										}
										
										urlConnection.setRequestProperty("Referer", "http://maps.google.de/maps");
										urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0");
										
										
									}
									catch(IOException e){
										systemLog.log("IOException while getting urlConnection from url"+ e.getMessage(),SystemLog.SHORT_ERROR_MESSAGE);
										urlConnection=null;
									}
									
									if(urlConnection!=null){
										
										urlConnection.setConnectTimeout(timeout);
										urlConnection.setReadTimeout(timeout);
										
										try{
											urlConnection.connect();	
										}catch(SocketException e){
											systemLog.log("SocketException while opening connection"+e.getMessage(),SystemLog.SHORT_ERROR_MESSAGE);
											urlConnection=null;
										} catch(IOException e){
											systemLog.log("IOException while opening connection"+e.getMessage(),SystemLog.SHORT_ERROR_MESSAGE);
											urlConnection=null;
										}
									}
									
									if(urlConnection!=null){
										try {
											urlConnectionInputStream = new BufferedInputStream(urlConnection.getInputStream());
										} catch(SocketTimeoutException e){
											systemLog.log("SocketTimeoutException while getting Input Stream from URLConnection",SystemLog.SHORT_ERROR_MESSAGE);
											urlConnectionInputStream=null;
										} catch(SocketException e){
											systemLog.log("SocketException while getting Input Stream from URLConnection",SystemLog.SHORT_ERROR_MESSAGE);
											urlConnectionInputStream=null;
										} catch (IOException e) {
											systemLog.log("IOException can not get InputStream from URLConnection",SystemLog.SHORT_ERROR_MESSAGE);
											
											String responseMessage=null;
											try {
												responseMessage = ((HttpURLConnection)urlConnection).getResponseMessage();
											} catch (IOException e1) {
												systemLog.log("IOException while getting response message",SystemLog.SHORT_ERROR_MESSAGE);
												responseMessage=null;
												e1.printStackTrace();
											}
											
											if(responseMessage!=null){
												if(responseMessage.equals("Forbidden")){
													systemLog.log("Google blocked this proxy, trying next one",SystemLog.DEBUG_INFO_MESSAGE);
												}
												else{
													if(responseMessage.equals("Not Found")){
														systemLog.log("This file does not exist: "+imageURL.toString(),SystemLog.DEBUG_INFO_MESSAGE);
														addToNotFoundList(currentImageToDownload.getX(),currentImageToDownload.getY(),currentImageToDownload.getZ());
														filesToDownload.fileNotFound(currentImageToDownload);
														downloadable = false;	
													}
													else{
														systemLog.log("responseMessage is not Forbidden or Not Found",SystemLog.DEBUG_INFO_MESSAGE);
														e.printStackTrace();
													}
												}
											}
											urlConnectionInputStream=null;
										}
									}
									
									if(urlConnectionInputStream!=null){
										
										try{
											bi = ImageIO.read(urlConnectionInputStream);
										}catch(SocketTimeoutException e){
											systemLog.log("SocketTimeoutException while downloading",SystemLog.SHORT_ERROR_MESSAGE);
											bi=null;
										}
										catch(IOException e){
											systemLog.log("IOException while downloading image",SystemLog.SHORT_ERROR_MESSAGE);
											bi=null;
										}finally{
											try {
												urlConnectionInputStream.close();
											} catch (IOException e) {
												systemLog.log("Can not close inputstream from urlconnection.", SystemLog.DEBUG_INFO_MESSAGE);
											}
										}
									}
								
									if(bi!=null){
										
										try {
											ImageIO.write(bi, "png", saveFile);
										} catch (IOException e) {
											systemLog.log("IOException while saving downloaded image",SystemLog.SHORT_ERROR_MESSAGE);
											e.printStackTrace();
										}
										
										systemLog.log("Downloaded: "+saveFile.getName(),SystemLog.INFO_MESSAGE);
										filesToDownload.downloaded();
										publish(bi);
										setProgress(filesToDownload.getNumberOfDownloadedFiles()*100/filesToDownload.getTotalNumberOfFiles());
										downloadable = false;
									}
								}
							}
							downloadWorkDone();
						}
					}.start();
				}
		
				systemLog.log("finished worker thread creation",SystemLog.INFO_MESSAGE);
				return null;
			}
			
			@Override
		     protected void process(List<BufferedImage> chunks) {
		         for (int i =0; i<chunks.size();i++) {
		        	 previewImage.getGraphics() .drawImage(chunks.get(i),0,0,downloadPanelTop);
		        	 downloadPanelTop.updateUI();
		         }
		        statusTextText = "Status: " +filesToDownload.getNumberOfDownloadedFiles()+" of " + filesToDownload.getTotalNumberOfFiles() +" loaded" ;
		        statusText.setText(statusTextText);
		        statusPanel.updateUI();
		     }
		};
		
		pcl = new PropertyChangeListener(){

			@Override
			public void propertyChange(PropertyChangeEvent pce) {
				
				if(pce.getPropertyName().equals("progress")){
		        	statusDownloadProgress.setValue(downloadWorker.getProgress());
		        	
		        	if(downloadWorker.getProgress()==100){
		        		cancelButton.setEnabled(false);
						downloadButton.setEnabled(true);
						xStartTextField.setEditable(true);
						xEndTextField.setEditable(true);
						yStartTextField.setEditable(true);
						yEndTextField.setEditable(true);
						zHeightTextField.setEditable(true);
						loadFinishedTimer.start();
		        	}
				}
			}
		};
		downloadWorker.addPropertyChangeListener(pcl);
		
		downloadWorker.execute();
	}
	
	private synchronized void addToNotFoundList(int x,int y,int z){
		
		try {
			notFoundListWriter = new BufferedWriter(new FileWriter(notFoundListFile,true));
			notFoundListWriter.append("x="+x+"y="+y+"z="+z);
			systemLog.log("added "+ "x="+x+"y="+y+"z="+z+" to notFoundList",SystemLog.INFO_MESSAGE);
			notFoundListWriter.newLine();
			notFoundListWriter.close();
		} catch (IOException e) {
			systemLog.log("Can not add imageentry to not found list", SystemLog.SHORT_ERROR_MESSAGE);
			e.printStackTrace();
		}
	}
	
	private synchronized TreeSet<String> getNotFoundList(){
		
		TreeSet<String> list = new TreeSet<String>();
		try {
			notFoundListReader = new BufferedReader(new FileReader(notFoundListFile));
			String line = null;
	        while((line = notFoundListReader.readLine()) != null) {
	          list.add(line);
	        }
	        notFoundListReader.close();
		} catch (IOException e) {
			systemLog.log("Can not create notFoundList", SystemLog.SHORT_ERROR_MESSAGE);
			e.printStackTrace();
		}
		
		return list;
	}

	private String nextAdress(int x, int y, int z){
		// example for imageAdress: "http://khm3.google.de/kh/v=78&x=68881&s=&y=45137&z=17&s=Gali"
		
		BigInteger xbig =  BigInteger.valueOf(x);
		BigInteger ybig =  BigInteger.valueOf(y);
		
		int i = ((ybig.multiply(xbig.add( BigInteger.valueOf(2)))).mod(BigInteger.valueOf(baseURLs.length))).intValue();
		 
		String salt = "Galileo".substring(0,(x*3+y)%8);
		
		String middleSalt = "";
		
		if(y>=Math.pow(10, 4)&&y<Math.pow(10, 5)){
			middleSalt="&s=";
		}
			
		return (baseURLs[i]+"x="+x+middleSalt+"&y="+y+"&z="+z+"&s="+salt);
	}
	
	public void init(){

		System.setProperty("http.agent", "");
		
		pictureObjectDirectory = new File(new File("").getAbsolutePath()+"//savedData//");
		if(!pictureObjectDirectory .exists()){
			pictureObjectDirectory.mkdir();
		}
		
		notFoundListFile = new File(new File("").getAbsolutePath()+"//notFoundList.txt");
		
		
		
		baseURLs[0] = "http://khms0.google.de/kh/v="+ VNUMBER +"&src=app"+"&";
		baseURLs[1] = "http://khms1.google.de/kh/v="+ VNUMBER +"&src=app"+"&";
		
		
	}
	
	private void initUI(){
		try {
			SwingUtilities.invokeAndWait(
				new Runnable(){
					public void run(){
						screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
						screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
						
						xStartLabel = new JLabel("xStart");
						xEndLabel = new JLabel("xEnd");
						yStartLabel = new JLabel("yStart");
						yEndLabel = new JLabel("yEnd");
						zHeightLabel = new JLabel("zHeight");
						
						xStartLabel.setHorizontalAlignment(SwingConstants.CENTER);
						xEndLabel.setHorizontalAlignment(SwingConstants.CENTER);
						yStartLabel.setHorizontalAlignment(SwingConstants.CENTER);
						yEndLabel.setHorizontalAlignment(SwingConstants.CENTER);
						zHeightLabel.setHorizontalAlignment(SwingConstants.CENTER);
						
						xStartLabel.setBorder(BorderFactory.createLineBorder(Color.black));
						xEndLabel.setBorder(BorderFactory.createLineBorder(Color.black)); 
						yStartLabel.setBorder(BorderFactory.createLineBorder(Color.black));
						yEndLabel.setBorder(BorderFactory.createLineBorder(Color.black)); 
						zHeightLabel.setBorder(BorderFactory.createLineBorder(Color.black)); 
						
						xStartTextField = new JTextField();
						xEndTextField = new JTextField();
						yStartTextField = new JTextField();
						yEndTextField = new JTextField();
						zHeightTextField = new JTextField();
						
						xStartTextField.setHorizontalAlignment(SwingConstants.CENTER);
						xEndTextField.setHorizontalAlignment(SwingConstants.CENTER);
						yStartTextField.setHorizontalAlignment(SwingConstants.CENTER);
						yEndTextField.setHorizontalAlignment(SwingConstants.CENTER);
						zHeightTextField.setHorizontalAlignment(SwingConstants.CENTER);
						
						xStartTextField.setBorder(BorderFactory.createLineBorder(Color.black)); 
						xEndTextField.setBorder(BorderFactory.createLineBorder(Color.black)); 
						yStartTextField.setBorder(BorderFactory.createLineBorder(Color.black)); 
						yEndTextField.setBorder(BorderFactory.createLineBorder(Color.black)); 
						zHeightTextField.setBorder(BorderFactory.createLineBorder(Color.black)); 
						
						downloadButton= new JButton("download images");
						downlaodAction = new ActionListener(){

							@Override
							public void actionPerformed(ActionEvent e) {
								
								try{
									int n1,n2,n3,n4,n5;
									n1=new Integer(xStartTextField.getText()).intValue();
									n2=new Integer(xEndTextField.getText()).intValue();
									n3=new Integer(yStartTextField.getText()).intValue();
									n4=new Integer(yEndTextField.getText()).intValue();
									n5=new Integer(zHeightTextField.getText()).intValue();
									downloadButton.setEnabled(false);
									try{
										downloadImages(n1,n2,n3,n4,n5);
										downloadButton.setEnabled(false);
										cancelButton.setEnabled(true);
										xStartTextField.setEditable(false);
										xEndTextField.setEditable(false);
										yStartTextField.setEditable(false);
										yEndTextField.setEditable(false);
										zHeightTextField.setEditable(false);
									}
									catch(IllegalArgumentException iae){
										JOptionPane.showMessageDialog(downloadFrame, "your endvalues are bigger than your startvalues", "Invalid input", JOptionPane.ERROR_MESSAGE);
									}
								}
								catch(NumberFormatException nfe){
									JOptionPane.showMessageDialog(downloadFrame, "your input has to be numbers", "Invalid input", JOptionPane.ERROR_MESSAGE);
								}
							}
						};
						downloadButton.addActionListener(downlaodAction);
						
						cancelButton = new JButton("cancel");
						cancelButton.setEnabled(false);
						cancleButtonAction = new ActionListener(){

							@Override
							public void actionPerformed(ActionEvent arg0) {
								if(!isDownloadCancelled()){
									cancelDownload();
									statusDownloadProgress.setIndeterminate(true);
									cancelButton.setEnabled(false);
								}
							}
						};
						cancelButton.addActionListener(cancleButtonAction);
						
						loadFinishedAction = new ActionListener(){

							@Override
							public void actionPerformed(ActionEvent arg0) {
								statusText.setText("no loading jobs");
								statusDownloadProgress.setIndeterminate(false);
								statusDownloadProgress.setValue(0);
								loadFinishedTimer.stop();
							}
						};
						loadFinishedTimer = new Timer (4000,loadFinishedAction );
						
						statusFrame = new JDialog(mainFrame,"DownloadStatus",false);
						statusFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
						statusPanel = new JPanel(new BorderLayout(),true);
						statusText = new JLabel("no download jobs");
						statusDownloadProgress = new JProgressBar();
						statusDownloadProgress.setPreferredSize(new Dimension(screenWidth*5/28,screenHeight/21));
						statusDownloadProgress.setMinimum(0);
						statusDownloadProgress.setMaximum(100);
						statusPanel.add(cancelButton,BorderLayout.EAST);
						statusPanel.add(statusText,BorderLayout.WEST);
						statusFrame.add(statusDownloadProgress,BorderLayout.NORTH);
						statusFrame.add(statusPanel,BorderLayout.SOUTH);
						statusFrame.setResizable(false);
						statusFrame.pack();
						statusFrame.setLocation(mainFrame.getLocation().x+mainFrame.getWidth()+18,mainFrame.getLocation().y + screenHeight*5/42);
						
						downloadPanelBottom = new JPanel(new GridLayout(5,2));
						downloadPanelBottom.add(xStartLabel);
						downloadPanelBottom.add(xStartTextField);
						downloadPanelBottom.add(xEndLabel);
						downloadPanelBottom.add(xEndTextField);
						downloadPanelBottom.add(yStartLabel);
						downloadPanelBottom.add(yStartTextField);
						downloadPanelBottom.add(yEndLabel);
						downloadPanelBottom.add(yEndTextField);
						downloadPanelBottom.add(zHeightLabel);
						downloadPanelBottom.add(zHeightTextField);
						
						downloadPanelTop= new JPanel(new BorderLayout(),true);
						downloadPanelTop.setMinimumSize(new Dimension(256,256));
						downloadPanelTop.setPreferredSize(new Dimension(screenWidth*5/28,screenWidth*5/28));
						previewImage = new BufferedImage(256,256,BufferedImage.TYPE_INT_ARGB);
						downloadPanelTop.add(new JLabel(new ImageIcon(previewImage)),BorderLayout.CENTER);
						
						downloadFrame = new JDialog(mainFrame,"Downloader",false);
						downloadFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
						downloadFrame.setResizable(false);
						
						downloadFrame.add(downloadPanelTop,BorderLayout.NORTH);
						downloadFrame.add(downloadPanelBottom,BorderLayout.CENTER);
						downloadFrame.add(downloadButton,BorderLayout.SOUTH);
						
						downloadFrame.pack();
						downloadFrame.setLocation(mainFrame.getLocation().x+mainFrame.getWidth()+18,mainFrame.getLocation().y+screenHeight*4/17);
						
						downloadFrame.setVisible(true);
						statusFrame.setVisible(true);
					}
				}
			);
		} catch (InterruptedException e) {
			systemLog.log("InterruptedException in Downloadsystem GUI creation",SystemLog.SHORT_ERROR_MESSAGE);
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			systemLog.log("InvocationTargetException in Downloadsystem GUI creation",SystemLog.SHORT_ERROR_MESSAGE);
			e.printStackTrace();
		}
	}
	
	private synchronized void cancelDownload(){
		cancleDownload = true;
	}
	
	private synchronized boolean isDownloadCancelled(){
		return cancleDownload;
	}
	
	private synchronized void downloadWorkDone(){
		workDoneCounter++;
		
		systemLog.log(workDoneCounter+"/"+downloadThreadCount,SystemLog.DEBUG_INFO_MESSAGE);
		if(workDoneCounter==downloadThreadCount){
			SwingUtilities.invokeLater(new Runnable(){

				@Override
				public void run() {
					cancelButton.setEnabled(false);
					downloadButton.setEnabled(true);
					xStartTextField.setEditable(true);
					xEndTextField.setEditable(true);
					yStartTextField.setEditable(true);
					yEndTextField.setEditable(true);
					zHeightTextField.setEditable(true);
					loadFinishedTimer.start();
				}
			});
		}
	}
}
